<template>
    <div class="market">
        <div v-for="(item, index) in state.applicationList" :key="`k${index}`" class="application_item">
            <div class="application_item_title">{{ item.title }}</div>
            <Card :data="item">
                <template #btn>
                    <el-button v-if="item.explain" plain @click="openExplain">使用说明</el-button>
                    <el-button type="primary" @click="onHandle(item)">{{ item.btn }}</el-button>
                </template>
            </Card>
        </div>
        <ConfirmDialog :data="confirmScrmDiaProps" @confirm="onScrmConfirm" />
        <ConfirmDialog :data="confirmErpDiaProps" @confirm="onErpConfirm" />
        <ConfirmDialog :data="confirmErpStatusProps" @confirm="onErpStatusConfirm" />
        <ScrmDia ref="ScrmDiaRef" />
        <ErpDia ref="ErpDiaRef" />
    </div>
</template>

<script setup>
import Card from './card.vue';
import ScrmDia from './scrmDia.vue';
import ErpDia from './erpDia.vue';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import request from '@/request';
import constants from '@/commons/constants';
import { throttle } from '@/commons/utils';
import { applicationChangeStatus, openExplain } from '@/hooks';
import { ElMessage } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';

const APPLICATION_BUTTON = constants.APPLICATION_BUTTON;
const TITLE = {
    1: 'SCRM',
    2: '电商ERP'
};
const state = reactive({
    applicationList: [], // 应用列表
    currentRow: {} // 当前应用数据
});

// 获取应用列表
const getApplicationList = async () => {
    const res = await request('applicationList');
    const data = Array.isArray(res.data) ? res.data : [];
    state.applicationList = data.map(item => {
        let btn = APPLICATION_BUTTON[item.state];
        // 1-scrm 2-聚水潭
        if (item.type === 1) {
            btn = APPLICATION_BUTTON[item.state === 1 ? 1 : item.state === 2 ? 4 : '--'];
        } else {
            btn = APPLICATION_BUTTON[item.state === 1 ? 1 : item.status === 1 ? 3 : 2];
            // 聚水潭授权过期
            if (item.isExpired) {
                btn = APPLICATION_BUTTON[90];
            }
        }
        return {
            ...item,
            applicationId: item.applicationId,
            title: TITLE[item.type],
            avatar: item.img,
            name: item.name,
            desc: item.desc,
            tag: item.state === 2,
            btn,
            explain: [2].includes(item.type),
            isExpired: item.isExpired
        };
    });
};

// 开通 SCRM
const confirmScrmDiaProps = reactive({
    show: false,
    title: '提示',
    content: '确定开通客易达SCRM吗？'
});

const ScrmDiaRef = ref(null);
const onScrmConfirm = async () => {
    await request('applicationOpen', { applicationId: state.currentRow.applicationId });
    getApplicationList();
    confirmScrmDiaProps.show = false;
    ScrmDiaRef.value.onOpen(state.currentRow);
};

const onScrm = v => {
    if (v.state === 1) {
        confirmScrmDiaProps.show = true;
        return;
    } else {
        ScrmDiaRef.value.onOpen(v);
    }
};

// 开通 ERP
const confirmErpDiaProps = reactive({
    show: false,
    title: '提示',
    width: '600px',
    content: '请在新窗口中完成ERP的授权，授权成功后请点击“授权成功”。',
    closeText: '授权失败，稍后重试',
    confirmText: '授权成功'
});
const confirmErpStatusProps = reactive({
    show: false,
    title: '提示',
    width: '400px',
    content: '',
    closeText: '取消',
    confirmText: '确定'
});
const ErpDiaRef = ref(null);

const onOpenErp = async v => {
    const res = await request('erpAuthUrl');
    /*
        status: 1 未授权
        status: 2 已授权 未绑定店铺
        status: 3 已授权 已绑定店铺
    */
    const data = res.data || {};
    switch (data.status) {
        case 1:
            confirmErpDiaProps.show = true;
            window.open(data.url);
            break;
        case 2:
            ErpDiaRef.value.onOpen(v);
            break;
    }
};
const onErpStatusConfirm = throttle(
    async () => {
        const v = state.currentRow;
        await applicationChangeStatus({ applicationId: v.applicationId, status: v.status === 1 ? 2 : 1 });
        const message = v.status === 1 ? '停用成功' : '启用成功';
        confirmErpStatusProps.show = false;
        ElMessage.success(message);
        getApplicationList();
    },
    1500,
    { trailing: false }
);
// 获取授权 url
const onErp = async v => {
    // 未开通 || 开通后授权过期
    if (v.state === 1 || (v.state === 2 && v.isExpired)) {
        onOpenErp(v);
        return;
    }
    // 已开通
    if (v.state === 2) {
        confirmErpStatusProps.content = v.status === 1 ? '确定停用吗?' : '确定启用吗?';
        confirmErpStatusProps.show = true;
        return;
    }
};
const onErpConfirm = async () => {
    const res = await request('erpAuthUrl');
    if (res.data?.status === 2) {
        confirmErpDiaProps.show = false;
        ErpDiaRef.value.onOpen(state.currentRow);
    } else {
        ElMessage.error('请先授权');
    }
};

const onHandle = v => {
    state.currentRow = v;
    switch (v.type) {
        case 1:
            onScrm(v);
            break;
        case 2:
            onErp(v);
            break;
    }
};

onMounted(getApplicationList);
</script>

<style lang="scss" scoped>
.market {
    display: flex;
    flex-direction: column;
    row-gap: 36px;
    .application_item {
        .application_item_title {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            &::before {
                display: inline-block;
                content: '';
                width: 4px;
                height: 16px;
                margin-right: 6px;
                background: #ff6b00;
            }
        }
    }
}
</style>
